package download;

import java.io.IOException;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.blobstore.BlobKey;
import com.google.appengine.api.blobstore.BlobInfo;
import com.google.appengine.api.blobstore.BlobInfoFactory;
import com.google.appengine.api.blobstore.BlobstoreService;
import com.google.appengine.api.blobstore.BlobstoreServiceFactory;
import com.google.appengine.api.blobstore.dev.BlobInfoStorage;
import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.EntityNotFoundException;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;

@SuppressWarnings("serial")
public class DownloadMediaServlet extends HttpServlet {
	private BlobstoreService blobstoreService = BlobstoreServiceFactory.getBlobstoreService();
	private DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
	
	public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		Key entityKey = KeyFactory.stringToKey(req.getParameter("entityKey"));
		Entity mediaInfo;
		try {
			mediaInfo = datastore.get(entityKey);
			BlobKey blobKey = (BlobKey) mediaInfo.getProperty("blobKey");
			// download the object from the blobstore
			
			resp.setHeader("Content-Disposition", "inline;filename=" + mediaInfo.getProperty("fileName"));
			blobstoreService.serve(blobKey, resp);
			
		} catch (EntityNotFoundException e) {
			// delete failed, redirect to a different page
		}

	}
}
